/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.colswe.solestac.view;

import java.awt.Color;
import java.util.List;
import javax.swing.JOptionPane;
import org.colswe.solestac.control.AdministrationControl;
import org.colswe.solestac.entity.ActualUser;
import org.colswe.solestac.VO.RoleVO;
import org.colswe.solestac.VO.UserVO;

/**
 *
 * @author Julian Pena
 * @version 1.0
 */
public class NewUser extends javax.swing.JPanel {
    
    private AdministrationControl ac = new AdministrationControl();
    /**
     * Creates new form NewUser
     */
    public NewUser() {
        initComponents();
        inicialize();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        cedulaTF = new javax.swing.JTextField();
        usuarioTF = new javax.swing.JTextField();
        rolCB = new javax.swing.JComboBox();
        reContrasenaTF = new javax.swing.JPasswordField();
        contrasenaTF = new javax.swing.JPasswordField();
        crearB = new javax.swing.JButton();

        setBackground(new java.awt.Color(255, 255, 255));
        setPreferredSize(new java.awt.Dimension(750, 650));
        setRequestFocusEnabled(false);
        setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16));
        jLabel1.setText("Rol:");
        add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 210, 110, 20));

        jLabel3.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16));
        jLabel3.setText("Cedula:");
        add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 40, 150, 20));

        jLabel4.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16));
        jLabel4.setText("Usuario:");
        add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 80, 140, 20));

        jLabel5.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16));
        jLabel5.setText("Contraseña:");
        add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 120, 140, 20));

        jLabel6.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16));
        jLabel6.setText("repetir contraseña:");
        add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 160, 160, 20));

        cedulaTF.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                cedulaTFKeyTyped(evt);
            }
        });
        add(cedulaTF, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 30, 180, -1));
        add(usuarioTF, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 70, 180, -1));

        rolCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        add(rolCB, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 200, 250, -1));
        add(reContrasenaTF, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 150, 180, -1));
        add(contrasenaTF, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 110, 180, -1));

        crearB.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16));
        crearB.setText("Crear");
        crearB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                crearBActionPerformed(evt);
            }
        });
        add(crearB, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 300, 80, 30));
    }// </editor-fold>//GEN-END:initComponents

    private void crearBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_crearBActionPerformed
        
        CleanTF();
        String pass = String.valueOf(contrasenaTF.getPassword());
        String repass = String.valueOf(reContrasenaTF.getPassword());
        
        UserVO uvo = new UserVO();
        uvo.setUsername(usuarioTF.getText().toLowerCase());
        uvo.setPassword(pass);
        uvo.setRepassword(repass);
        uvo.setRole((String)rolCB.getSelectedItem());
        uvo.setDocument(cedulaTF.getText());
        int res = ac.createUser(uvo);
        
        if(res == 0){               
            usuarioTF.setText("");
            contrasenaTF.setText("");
            reContrasenaTF.setText("");
            rolCB.setSelectedIndex(0);
            cedulaTF.setText("");
            showConfirmMssg("El usuario ha sido creado correctamente");        
            
            Principal principal = ActualUser.getInstance().getPrincipal();
            principal.userAdministration();
        }
        else if(res == -1){
            showWarningMssg("El nombre de usuario sólo puede tener número y letras");
            usuarioTF.setBackground(new Color(255,102,102));
            
        }
        else if(res == -2){
            showWarningMssg("El nombre de usuario debe tener entre 5 y 20 caracteres");
           usuarioTF.setBackground(new Color(255,102,102));
        }        
        else if(res == -3){
            showWarningMssg("La contrasena debe conterner al menos una letra Mayúscula, una minúscula y un número");
            contrasenaTF.setBackground(new Color(255,102,102));
        }
        else if(res == -4){
            showWarningMssg("La contrasena debe tener entre 5 y 30 caracteres");
            contrasenaTF.setBackground(new Color(255,102,102));
        }
        else if(res == -5){
            showWarningMssg("El nombre de usuario ya existe");
            usuarioTF.setBackground(new Color(255,102,102));
        }
        else if(res == -6){
            showWarningMssg("La contrasena y su confirmación no coinciden");
            reContrasenaTF.setBackground(new Color(255,102,102));
        }
        else if(res == -7){
            showWarningMssg("Cédula inválida");
            cedulaTF.setBackground(new Color(255,102,102));
        }
        else if(res == -8){
           
            showWarningMssg("Ocurrió un problema inesperado");
        }
        else if(res == -9){
            showErrorMssg("Seleccione un rol por favor");
        }
    }//GEN-LAST:event_crearBActionPerformed

    private void showConfirmMssg(final String Mssg){
        JOptionPane.showMessageDialog(this, Mssg);
    }
    private void showWarningMssg(final String Mssg){
        JOptionPane.showMessageDialog(this, Mssg, "Advertencia",JOptionPane.WARNING_MESSAGE);
    }
    
    private void showErrorMssg(final String Mssg){
        JOptionPane.showMessageDialog(this, Mssg, "Error", JOptionPane.ERROR_MESSAGE);
    }
    
     private void CleanTF(){
        usuarioTF.setBackground(Color.white);
        contrasenaTF.setBackground(Color.white);
        reContrasenaTF.setBackground(Color.white);
        cedulaTF.setBackground(Color.white);
    }
    
    
    private void cedulaTFKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cedulaTFKeyTyped
        char l = evt.getKeyChar();
        if(!Character.isDigit(l)){
            evt.consume();
        }
    }//GEN-LAST:event_cedulaTFKeyTyped

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField cedulaTF;
    private javax.swing.JPasswordField contrasenaTF;
    private javax.swing.JButton crearB;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPasswordField reContrasenaTF;
    private javax.swing.JComboBox rolCB;
    private javax.swing.JTextField usuarioTF;
    // End of variables declaration//GEN-END:variables

    private void inicialize() {
        rolCB.removeAllItems();
        List<RoleVO> roles = ac.getAllRoles();
        rolCB.addItem("--Seleccione Rol--");
        for(RoleVO rol: roles){
            rolCB.addItem(rol.getName());
        }
        CleanTF();
    }
}
